// backend/controllers/checkinController.js

const db = require('../config/db');
const moment = require('moment');

// Handle new check-in
exports.createCheckin = async (req, res) => {
    try {
        const { guest_id, room_id, checkin_date } = req.body;

        const [room] = await db.query('SELECT status FROM Rooms WHERE room_id = ?', [room_id]);
        if (room.length === 0 || room[0].status !== '空闲') {
            return res.status(400).json({ error: '房间不可用', message: '该房间当前不空闲或不存在。' });
        }

        const [guest] = await db.query('SELECT guest_id FROM Guests WHERE guest_id = ?', [guest_id]);
        if (guest.length === 0) {
            return res.status(400).json({ error: '客户不存在', message: '请先添加客户信息。' });
        }

        const [existingCheckin] = await db.query(
            'SELECT * FROM Checkins WHERE guest_id = ? AND room_id = ? AND status = "入住中"',
            [guest_id, room_id]
        );
        if (existingCheckin.length > 0) {
            return res.status(400).json({ error: '重复入住', message: '该客户已入住此房间。' });
        }

        const [result] = await db.query(
            'INSERT INTO Checkins (guest_id, room_id, checkin_date, status, total_amount) VALUES (?, ?, ?, "入住中", 0.00)',
            [guest_id, room_id, checkin_date]
        );

        // Update room status to '已入住'
        await db.query('UPDATE Rooms SET status = "已入住" WHERE room_id = ?', [room_id]);

        res.status(201).json({ message: '入住办理成功', checkinId: result.insertId });
    } catch (err) {
        console.error('办理入住错误:', err);
        res.status(500).json({ error: '办理入住失败', details: err.message });
    }
};

// Handle guest checkout
exports.checkout = async (req, res) => {
    try {
        const { id } = req.params; // checkin_id from URL
        const { check_out_time } = req.body;

        console.log(`[Checkout] Attempting checkout for checkin_id: ${id}`);
        console.log(`[Checkout] Provided check_out_time: ${check_out_time}`);

        const [checkin] = await db.query('SELECT * FROM Checkins WHERE checkin_id = ?', [id]);
        if (checkin.length === 0) {
            console.warn(`[Checkout] Checkin record not found for ID: ${id}`);
            return res.status(404).json({ error: '入住记录未找到。' });
        }
        if (checkin[0].status === '已退房') {
            console.warn(`[Checkout] Checkin record ${id} already checked out.`);
            return res.status(400).json({ error: '重复退房', message: '该入住记录已退房。' });
        }

        const room_id = checkin[0].room_id;
        const checkin_date = moment(checkin[0].checkin_date);
        const actual_checkout_date = moment(check_out_time);

        console.log(`[Checkout] checkin_date: ${checkin_date.format()}`);
        console.log(`[Checkout] actual_checkout_date: ${actual_checkout_date.format()}`);

        const [roomDetails] = await db.query('SELECT price FROM Rooms WHERE room_id = ?', [room_id]);
        if (roomDetails.length === 0) {
            console.error(`[Checkout] Room details not found for room_id: ${room_id}`);
            return res.status(500).json({ error: '房间信息缺失，无法计算费用。' });
        }
        const roomPricePerDay = roomDetails[0].price;

        // Calculate days stayed (round up to ensure full day is charged for partial day)
        // Duration in days, adding 1 to include the checkout day.
        const duration = actual_checkout_date.diff(checkin_date, 'days') + 1;
        const roomCharges = roomPricePerDay * duration;

        console.log(`[Checkout] Room price per day: ${roomPricePerDay}`);
        console.log(`[Checkout] Duration (days): ${duration}`);
        console.log(`[Checkout] Calculated room charges: ${roomCharges}`);

        const updatedTotalAmount = parseFloat(checkin[0].total_amount || 0) + parseFloat(roomCharges);

        console.log(`[Checkout] Existing total_amount: ${checkin[0].total_amount}`);
        console.log(`[Checkout] New total_amount (including room charges): ${updatedTotalAmount.toFixed(2)}`);


        // Update Checkins table: checkout_date, status, total_amount
        await db.query(
            'UPDATE Checkins SET checkout_date = ?, status = "已退房", total_amount = ? WHERE checkin_id = ?',
            [check_out_time, updatedTotalAmount.toFixed(2), id]
        );
        console.log(`[Checkout] Checkin ${id} status and amount updated.`);

        // Update room status to '空闲'
        await db.query('UPDATE Rooms SET status = "空闲" WHERE room_id = ?', [room_id]);
        console.log(`[Checkout] Room ${room_id} status updated to "空闲".`);


        res.status(200).json({ message: '退房成功', finalAmount: updatedTotalAmount.toFixed(2) });

    } catch (err) {
        console.error('办理退房错误:', err);
        res.status(500).json({ error: '办理退房失败', details: err.message });
    }
};

// Get all check-in records (for admin)
exports.getAllCheckins = async (req, res) => {
    try {
        const { status, room_number, guest_name, id_card, startDate, endDate, limit, offset } = req.query;
        let query = `
            SELECT
                c.checkin_id,
                c.checkin_date,
                c.checkout_date,
                c.total_amount,
                c.status,
                r.room_number,
                r.room_type,
                r.price AS room_price,
                g.name AS guest_name,
                g.id_card,
                g.phone
            FROM Checkins c
                     JOIN Rooms r ON c.room_id = r.room_id
                     JOIN Guests g ON c.guest_id = g.guest_id
            WHERE 1=1
        `;
        const countQuery = `
            SELECT COUNT(*) AS total
            FROM Checkins c
                     JOIN Rooms r ON c.room_id = r.room_id
                     JOIN Guests g ON c.guest_id = g.guest_id
            WHERE 1=1
        `;
        const params = [];
        const countParams = [];

        if (status) {
            query += ' AND c.status = ?';
            countQuery += ' AND c.status = ?';
            params.push(status);
            countParams.push(status);
        }
        if (room_number) {
            query += ' AND r.room_number LIKE ?';
            countQuery += ' AND r.room_number LIKE ?';
            params.push(`%${room_number}%`);
            countParams.push(`%${room_number}%`);
        }
        if (guest_name) {
            query += ' AND g.name LIKE ?';
            countQuery += ' AND g.name LIKE ?';
            params.push(`%${guest_name}%`);
            countParams.push(`%${guest_name}%`);
        }
        if (id_card) {
            query += ' AND g.id_card = ?';
            countQuery += ' AND g.id_card = ?';
            params.push(id_card);
            countParams.push(id_card);
        }
        if (startDate) {
            query += ' AND c.checkin_date >= ?';
            countQuery += ' AND c.checkin_date >= ?';
            params.push(startDate);
            countParams.push(startDate);
        }
        if (endDate) {
            query += ' AND c.checkin_date <= ?'; // 或者根据需求改为 checkout_date
            countQuery += ' AND c.checkin_date <= ?';
            params.push(endDate);
            countParams.push(endDate);
        }

        query += ' ORDER BY c.checkin_date DESC';

        if (limit && offset) {
            query += ' LIMIT ? OFFSET ?';
            params.push(parseInt(limit), parseInt(offset));
        }

        const [rows] = await db.query(query, params);
        const [totalResult] = await db.query(countQuery, countParams);
        const total = totalResult[0].total;

        res.status(200).json({ data: rows, total });

    } catch (err) {
        console.error('获取入住记录列表错误:', err);
        res.status(500).json({ error: '获取入住记录列表失败', details: err.message });
    }
};

// Get active check-in records (e.g., for dashboard)
exports.getActiveCheckins = async (req, res) => {
    try {
        const [rows] = await db.query(
            `SELECT
                 c.checkin_id,
                 c.checkin_date,
                 c.total_amount,
                 r.room_number,
                 r.room_type,
                 g.name AS guest_name,
                 g.id_card
             FROM Checkins c
                      JOIN Rooms r ON c.room_id = r.room_id
                      JOIN Guests g ON c.guest_id = g.guest_id
             WHERE c.status = '入住中'
             ORDER BY c.checkin_date DESC`
        );
        res.status(200).json(rows);
    } catch (err) {
        console.error('获取进行中入住记录错误:', err);
        res.status(500).json({ error: '获取进行中入住记录失败', details: err.message });
    }
};

// Get single check-in record by ID (for admin/checkin details page)
exports.getCheckinById = async (req, res) => {
    try {
        const { id } = req.params;
        const [rows] = await db.query(
            `SELECT
                 c.checkin_id,
                 c.guest_id,
                 c.room_id,
                 c.checkin_date,
                 c.checkout_date,
                 c.total_amount,
                 c.status,
                 r.room_number,
                 r.room_type,
                 r.price AS room_price,
                 g.name AS guest_name,
                 g.id_card,
                 g.phone
             FROM Checkins c
                      JOIN Guests g ON c.guest_id = g.guest_id
                      JOIN Rooms r ON c.room_id = r.room_id
             WHERE c.checkin_id = ?
            `, [id]);

        if (rows.length === 0) {
            return res.status(404).json({ error: '入住记录未找到。' });
        }
        const checkinData = rows[0];

        res.status(200).json(checkinData);
    } catch (err) {
        console.error('获取入住记录详情失败:', err);
        res.status(500).json({ error: '获取入住记录详情失败', details: err.message });
    }
};

// Get check-in records by guest ID card (客户端查询历史入住记录)
exports.getCheckinsByGuestCard = async (req, res) => {
    try {
        const { idCard } = req.params;
        const [rows] = await db.query(
            `SELECT
                 c.checkin_id,
                 r.room_number,
                 r.room_type,
                 r.price AS room_price,
                 c.checkin_date,
                 c.checkout_date,
                 c.status,
                 c.total_amount
             FROM Checkins c
                      JOIN Guests g ON c.guest_id = g.guest_id
                      JOIN Rooms r ON c.room_id = r.room_id
             WHERE g.id_card = ?
             ORDER BY c.checkin_date DESC`,
            [idCard]
        );
        res.status(200).json(rows);
    } catch (err) {
        console.error('获取客户入住记录错误:', err);
        res.status(500).json({ error: '获取客户入住记录失败', details: err.message });
    }
};
